<template>
    <div>
        <!--添加按钮和模态框-->
        <a-button type="primary" @click="showModal('add')">
            添加
        </a-button>
        <!--对话框-->
        <a-modal
                :visible="visible"
                :title= "modelTitle"
                :confirm-loading="confirmLoading"
                okText='确认'
                cancel-text="取消"
                @cancel="hideModel"
                @ok="submit"
        >
            <!--表单-->
            <a-form-model :model="form">
                <a-form-model-item label="父菜单">
                    <!--<a-input v-model="form.pid" />-->
                    <!--
                        v-model 双向绑定的值
                        dropdown-style 下拉样式
                        treeData   菜单数据
                        showSearch 是否开启搜索框(仅单选)
                        treeNodeFilterProp  输入搜索的属性
                    -->
                    <a-tree-select
                            v-model="form.pid"
                            style="width: 100%"
                            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                            :treeData="treeData"
                            :showSearch="true"
                            @change="changeSelect"
                            treeNodeFilterProp='title'
                            placeholder="请选择父节点"
                            allow-clear
                            tree-default-expand-all
                    >

                    </a-tree-select>
                </a-form-model-item>
                <a-form-model-item label="菜单名称">
                    <a-input v-model="form.title" placeholder="菜单名称"/>
                </a-form-model-item>

                <a-form-model-item label="前端路由">
                    <a-input v-model="form.router" placeholder="前端路由,设置二级菜单的跳转和刷新保持选中,保持跟前端二级路由一致"/>
                </a-form-model-item>
                <a-form-model-item label="后端路由">
                    <a-input v-model="form.url" placeholder="后端路由"/>
                </a-form-model-item>
                <a-form-model-item label="排序">
                    <a-input type="number" v-model="form.ordering" placeholder="排序"/>
                </a-form-model-item>
                <a-form-model-item label="状态">
                    <a-radio-group v-model="form.status">
                        <a-radio value="1">
                            启用
                        </a-radio>
                        <a-radio value="0">
                            禁用
                        </a-radio>
                    </a-radio-group>
                </a-form-model-item>
            </a-form-model>
        </a-modal>

        <!--表格-->
        <!--
            :columns="columns"  表头数据
            :data-source="data" 表格数据
            rowKey="id"   id为 data 中的一个属性
            :loading="loading" 表格是否load
            :pagination="pagination" 分页参数
            :childrenColumnName 树形结构列名
        -->
        <a-table :columns="columns" :data-source="data" rowKey="id" :loading="loading" :pagination="pagination" childrenColumnName="child_node" >
            <span slot="status" slot-scope="text, record, index" >
                <div v-if="text == 1">
                    <a-button type="primary" @click="changeActive(text, record, index)">已启用</a-button>
                </div>
                <div v-else>
                    <a-button type="danger" @click="changeActive(text, record, index)">已禁用</a-button>
                </div>
            </span>
            <!--插槽一定要在表格组件标签中-->
            <!--定义插槽渲染-->
            <!--
                slot="action" 表示是在columns（某列）中的表头值为action中插入标签，往这个位置插入插槽span中间的内容
                slot-scope="text, record, index"
                    text    表示当前行当前列的值
                    record  表示当前行的数据
                    index   表格索引
            -->
            <span slot="action" slot-scope="text, record, index">
                <a-button type="primary" @click="edit(text, record, index)">编辑</a-button>
                <!--气泡确认框-->
                <a-popconfirm
                        title="是否删除?"
                        @confirm="() => del(text, record, index)"
                >
                    <a-button type="danger">
                        删除
                    </a-button>
                </a-popconfirm>

            </span>

            <template slot="operation" slot-scope="text, record">
                <a-popconfirm
                        v-if="dataSource.length"
                        title="Sure to delete?"
                        @confirm="() => onDelete(record.key)"
                >
                    <a href="javascript:;">Delete</a>
                </a-popconfirm>
            </template>
        </a-table>

    </div>
</template>
<script>
    export default {
        // 在实例中使用 components 属性注册需要用到的组件
        //注册组件
        data() {
            return {
                //表格数据
                data : [],
                /**
                 * 表头数据
                 * title 为表头的标题
                 * dataIndex为列数据在数据项中对应的 key
                 * scopedSlots 对应插槽
                 */
                columns : [
                    {
                        title: '前端路由',
                        dataIndex: 'router',
                    },
                    {
                        title: '后端路由',
                        dataIndex: 'url',
                    },
                    {
                        title: '菜单名称',
                        dataIndex: 'title',
                    },
                    {
                        title: '状态',
                        dataIndex: 'status',
                        scopedSlots: {customRender: 'status'},
                    },
                    {
                        title: '操作',
                        dataIndex: 'action',
                        //使用插槽
                        scopedSlots: {customRender: 'action'},
                    },
                ],
                //表格load标志
                loading : true,
                //表格分页参数
                pagination: {
                    //pageNo: 2,
                    current: 1,
                    pageSize: 10, // 默认每页显示数量
                    showSizeChanger: true, // 显示可改变每页数量
                    pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
                    showTotal: total => `共 ${total} 条数据`, // 显示总数
                    onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize), // 改变每页数量时更新显示
                    onChange:(current,pageSize)=>this.changePage(current,pageSize),//点击页码事件
                    total:0 //总条数
                },
                //模态对话框标题
                modelTitle: '',
                //模态框是否显示
                visible: false,
                //表单load
                confirmLoading: false,

                //tree select 树选择
                treeData: [],

                //from 初始化
                form : {
                    id : 0,
                    pid : 0,
                    title : '',
                    router : '',
                    url : '',
                    ordering : 0,
                    status : '1',

                    //操作类型
                    operation_type : 'add',
                }
            };
        },
        //页面渲染之前,$el创建之后 去加载
        mounted() {
            //获取列表
            this.getList();
        },
        methods: {
            //获取列表
            getList(param) {
                //初始化分页参数
                if(param === undefined || param === null){
                    param = {
                        current : 1,
                        pageSize : 10
                    }
                }

                this.axios.get(process.env.VUE_APP_API_URL + this.urls.getMenus).then((data) => {
                    // console.log(data)
                    //修改loading 状态
                    this.loading = false;

                    //数据
                    this.data = data.data.data;

                    //树选择,下拉框重新构造
                    this.treeData = [
                        {
                            title : '顶级菜单',
                            value : 0,
                            key : 0
                        }
                    ];
                    if(this.treeData.length <= 1){
                        //转换树菜单选择
                        var res = this.convertToTreedata(data.data.data);

                        //脱掉一层再进行push
                        this.treeData.push(...res);
                    }

                });
            },
            //点击页码事件
            changePage(current,pageSize) {
                /*console.log(page, '当前页.......');
                console.log(pageSize, '每页大小.......');*/
                this.pagination.current = current;
                this.pagination.pageSize = pageSize;
                this.getList({
                    current : current,
                    pageSize : pageSize
                })
            },

            //每页显示数量改变的事件
            changePageSize(current, pageSize){
                /*console.log(current, '当前页.......');
                console.log(pageSize, '每页大小.......');*/
                this.pagination.current = current;
                this.pagination.pageSize = pageSize;
                this.getList({
                    current : current,
                    pageSize : pageSize
                })
            },


            /**
             * 树选择框,构造转换，转换后端数据为树形选择需要的数据
             * @param data  后端数据
             * @returns {[]}  返回结构
             */
            convertToTreedata(data){
                //console.log(data, '数据构造........')
                var returnData = [];
                //遍历数据
                for(var i = 0; i < data.length; i++){
                    var tempObj = {
                        title : data[i].title,
                        value : data[i].id,
                        key : data[i].id
                    };

                    //判断是否存在子节点，如果存在则递归
                    if('child_node' in data[i]){
                        tempObj.children = this.convertToTreedata(data[i].child_node);
                    }
                    //push到数据数组中
                    returnData.push(tempObj);
                }
                return returnData;
            },

            //树形菜单选中
            changeSelect(value, label, extra){
                //console.log(value, label,  extra, '菜单选中....');
                this.form.pid = value;
            },

            //显示模态对话框
            showModal(type) {
                //console.log(type, 'type........');
                //设置对话框标题
                type === 'add'? this.modelTitle = '添加':this.modelTitle = '编辑'
                this.visible = true;
            },
            //关闭模态框
            hideModel() {
                this.visible = false;
                this.resetForm();
            },

            //重置form状态
            resetForm(){
                this.form =  {
                    id : 0,
                    pid : 0,
                    title : '',
                    router : '',
                    url : '',
                    ordering : 0,
                    status : '1',

                    //操作类型
                    operation_type : 'add',
                }
            },

            //确认提交
            submit(){
                //基准地址
                var url = process.env.VUE_APP_API_URL;
                //接口路由
                if(this.form.operation_type === 'add'){
                    this.pagination.current = 1;
                    url += this.urls.menu_add;
                }
                if(this.form.operation_type === 'edit'){
                    url += this.urls.menu_edit;
                }
                if(this.form.operation_type === 'del'){
                    url += this.urls.menu_del;
                }
                if(this.form.operation_type === 'change_status'){
                    url += this.urls.menu_change_status;
                }
                //发送请求
                this.axios.post(url, this.form).then((data) => {

                    //错误提示
                    /*if(data.data.code !== 200){
                        this.$message.error(data.data.msg);
                        return;
                    }*/

                    //重新刷新表格
                    this.data = this.getList()
                    //恢复默认
                    this.resetForm();
                    //关闭按钮的load状态
                    this.confirmLoading = false;
                    //关闭模态框
                    this.visible = false;

                    //改变页码
                    if(this.form.operation_type === 'add'){
                        this.pagination.current = 1;
                    }
                });
            },
            //编辑
            edit(text, record, index) {
                //console.log(record);
                //设置模态框的form表单的值和选中
                this.form.id = record.id;
                this.form.pid = record.pid;
                this.form.title = record.title;
                this.form.router = record.router;
                this.form.url = record.url;
                this.form.ordering = record.ordering;
                this.form.status = ''+record.status;
                //切换操作类型
                this.form.operation_type = 'edit';

                //显示模态框
                this.showModal();
            },

            //编辑
            del(text, record, index) {
                //console.log('删除.........');
                this.form.id = record.id;
                //切换操作类型
                this.form.operation_type = 'del';
                //提交
                this.submit();
            },

            //改变状态
            changeActive(text, record, index) {
                //console.log(record)
                this.form.id = record.id;
                //切换操作类型
                this.form.operation_type = 'change_status';
                //提交
                this.submit();
            },

        },
    };
</script>
